package com.datastructures.stack;

import java.util.Scanner;

/**
 * 数组模拟栈
 *
 * @author MaoLin Wang
 * @date 2019/10/2017:00
 */
public class ArrayStackDemo {
    public static void main(String[] args) {

        ArrayStack arrayStack = new ArrayStack(5);
       arrayStack.push(1);
       arrayStack.push(2);
       arrayStack.push(3);
        System.out.println(arrayStack.top());
        while (!arrayStack.isEmpty()){
            System.out.println(arrayStack.pop());
        }


    }
}

class ArrayStack {
    private int maxSize;
    private int[] stack;
    private int top = -1;

    public ArrayStack(int maxSize) {
        if (maxSize>100){
            throw new IllegalArgumentException("栈最多存放100个元素");
        }
        this.maxSize = maxSize;
        stack = new int[this.maxSize];
    }

    //栈满
    public boolean isFull() {
        return top == maxSize - 1;
    }

    public boolean isEmpty() {
        return top == -1;
    }

    public void push(int value) {
        if (isFull()) {
           throw new RuntimeException("栈已满！");
        }
        top++;
        stack[top] = value;
    }

    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈空");
        }
        int value = stack[top--];

        return value;
    }

    public int top(){
        if (!isEmpty()){
            return stack[top];
        }
        throw new RuntimeException("栈空");
    }
    //遍历
    public void printData() {
        if (isEmpty()) {
            System.out.println("栈空");
            return;
        }
        for (int i = top; i >= 0; i--) {
            System.out.println(stack[i]);
        }
    }
}
